package top.lshaci.learning.nio.chat;

import cn.hutool.core.util.StrUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * GroupChatClient
 *
 * @author lshaci
 * @since 1.0.0
 */
public class GroupChatClient {

    private final Selector selector;

    private final SocketChannel socketChannel;

    public GroupChatClient(String server, int port) throws IOException {
        this.selector = Selector.open();
        this.socketChannel = SocketChannel.open(new InetSocketAddress(server, port));
        this.socketChannel.configureBlocking(false);
        this.socketChannel.register(this.selector, SelectionKey.OP_READ);
    }

    public void send(String msg) throws IOException {
        System.err.println(this.socketChannel.getLocalAddress() + " => 发送消息：" + msg);
        final ByteBuffer byteBuffer = StrUtil.byteBuffer(msg, "UTF-8");
        this.socketChannel.write(byteBuffer);
    }

    public void receive() throws IOException {
        while (true) {
            final int count = this.selector.select(1000);
            if (count > 0) {
                final Set<SelectionKey> selectionKeys = this.selector.selectedKeys();
                final Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    final SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isReadable()) {
                        final SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        final ByteBuffer byteBuffer = ByteBuffer.allocate(8192);
                        socketChannel.read(byteBuffer);
                        final String msg = StrUtil.str(byteBuffer.array(), Charset.defaultCharset());
                        System.out.println(this.socketChannel.getLocalAddress() + " => 接收到消息：" + msg);
                    }
                    iterator.remove();
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        GroupChatClient client = new GroupChatClient("127.0.0.1", 6677);
        new Thread(() -> {
            try {
                client.receive();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            final String msg = scanner.nextLine();
            client.send(msg);
        }
    }
}
